package com.hanshg.cherry.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanshg.cherry.base.core.Constants;
import com.hanshg.cherry.base.result.ResponseCode;
import com.hanshg.cherry.util.core.StringUtils;
import com.hanshg.cherry.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName VerifyCodeFilter
 * @Description 验证码 拦截器
 * @Author 柠檬水
 * @Date 2020/4/11 20:51
 * @Version 1.0
 **/
@Configuration
@Slf4j
public class VerifyCodeFilter extends GenericFilter {

    private final RedisUtil redisUtil;

    public VerifyCodeFilter(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 验证码过滤器
     *
     * @param servletRequest  servlet请求
     * @param servletResponse servlet响应
     * @param filterChain     过滤器链
     * @throws IOException      ioexception
     * @throws ServletException servlet异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //判断是否为登录操作
        if (Constants.SUBMIT_POST.equalsIgnoreCase(request.getMethod())&& Constants.LOGIN_PATH.equals(request.getServletPath())){
            String verifyCode = request.getParameter("verifyCode");
            String login_verify = (String) redisUtil.get(Constants.LOGIN_VERIFY_SESSION);;
            log.info("输入验证码："+verifyCode+",Redis获取的验证码："+login_verify);
            if (StringUtils.isEmpty(verifyCode) || StringUtils.isEmpty(login_verify) || !login_verify.equalsIgnoreCase(verifyCode)){
                //验证码错误
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString(ResponseCode.VERIFY_CODE));
                out.flush();
                out.close();
                return;
            }else {
                filterChain.doFilter(request,response);
            }
        }else {
            filterChain.doFilter(request,response);
        }
    }
}
